//
//  MyWorkSummaryViewController.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 16/12/20.
//  Copyright © 2016年 com.xtion.crm. All rights reserved.
//

#import "MyWorkSummaryViewController.h"
#import "WorkSummaryCell.h"
#import "WorkSummaryList.h"
#import "WorkSummaryDetailViewController.h"
#import "WorkSummaryEmptyCell.h"
#import "LeaderCommitWorkSummaryViewController.h"

NSString *const MyWorkSummaryViewControllerTitleParamKey = @"MyWorkSummaryViewControllerTitleParamKey";
NSString *const MyWorkSummaryViewControllerSourceTypeParamKey = @"MyWorkSummaryViewControllerSourceTypeParamKey";

@interface MyWorkSummaryViewController ()
{
    RSWDataOperation *_manager;
    
    NSDate *_lastUpdatetime;
    BOOL _bSearching;
    
    NSInteger _pageSize;
    NSInteger _pageIndex;
    
    NSMutableArray *_datas;
    NSMutableArray *_searchDatas;
    
    WorkSummarySourceType _sourceType;
}
@end

@implementation MyWorkSummaryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkSession];
    
    NSString *title = self.param[MyWorkSummaryViewControllerTitleParamKey];
    [self setBackNavigateItemTitle:title];
    
    self.view.backgroundColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStylef1f4f7Color];
    
    [self initVariable];
    [self initUI];

    [_manager getMyWorkSummarySourceType:_sourceType pageIndex:_pageIndex pageSize:_pageSize completion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         _bRefreshing = NO;
         
         [self requestComplete:nil funcationName:@"getMyWorkSummary" result:nResult output:list error:error];
     }];
}

- (void)initVariable
{
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    _searchDatas = [NSMutableArray new];
    _datas = [NSMutableArray new];
    
    _lastUpdatetime = [NSDate date];
    _pageIndex = 1;
    _pageSize = 20;
    
    _sourceType = [self.param[MyWorkSummaryViewControllerSourceTypeParamKey] integerValue];
    
    [self addMainThreadObserverWithDictionarySelector:@{RSWDataOperationWorkSummaryModifyNotification:
                                                            @"observerRSWDataOperationWorkSummaryModifyNotification:"
                                                        ,RSWDataOperationWorkSummaryDeleteNotification:@"observerRSWDataOperationWorkSummaryDeleteNotification:"}];
}

- (void)initUI
{
    [self createTableView:XUITabelViewStyleTypePlain|XUITabelViewStyleTypeRefresh];
    _ctable.separatorExistFollowCell = YES; 
}

-(void)viewControllerWillDealloc
{
    [super viewControllerWillDealloc];
    [_manager terminateRequest];
    [self removeObserver];
}

-(NSMutableArray*)workSummaryData;
{
    if(_bSearching == YES)
        return _searchDatas;
    
    return _datas;
}

-(void)requestComplete:(XMSDataOperationManager *)dom funcationName:(NSString *)szFuncationname result:(NSInteger)nResult output:(id)output error:(NSError *)error
{
    _bRefreshing = NO ;
    
    if([szFuncationname isEqualToString:@"getMyWorkSummary"])
    {
        [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
         {
             switch(requestResult)
             {
                 case YES:
                 {
                     [_datas removeAllObjects];
                     
                     NSArray *ar = output;
                     ar = [self insertEmptyWithOriginArray:_datas newArray:ar];
                     
                     [_datas addObjectsFromArray:ar]; 
                     
                     if(_datas.count >= _pageSize)
                         [_ctable createLoadMoreView];
                     else
                         [_ctable removeLoadMoreView];
                     
                     [_ctable reloadData];
                     
                     break;
                 }
                 default:
                 {
                     [UIAlertView showErrorMsg:@"数据请求失败"];
                     break;
                 }
             }
         }];
    }
    else if([szFuncationname isEqualToString:@"getMyWorkSummaryMore"])
    {
        [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
         {
             switch(requestResult)
             {
                 case YES:
                 {
                     if(((NSArray*)output).count > 0)
                     {
                         NSArray *ar = output;
                         
                         ar = [self insertEmptyWithOriginArray:_datas newArray:ar];
                         
                         [_datas removeAllObjects];
                         [_datas addObjectsFromArray:ar];
                         
                         [_ctable reloadData];
                     }
                     else
                         [_ctable removeLoadMoreView];
                     
                     break;
                 }
                 default:
                 {
                     [UIAlertView showErrorMsg:@"数据获取失败"];
                     break;
                 }
             }
         }];
    }
}

-(NSArray*)insertEmptyWithOriginArray:(NSArray*)oriArray newArray:(NSArray*)newArray
{
    NSMutableArray *ar = [NSMutableArray arrayWithArray:oriArray];
    
    for(NSUInteger i = 0 ; i < newArray.count ; i++)
    {
        WorkSummaryList *newL = newArray[i];
        
        if(i > 0)
        {
            WorkSummaryList * dtl = [WorkSummaryList new];
            dtl.type = WorkSummaryListEmpty;
            [ar addObject:dtl];
        }
        
        {
            WorkSummaryList * dtl = [WorkSummaryList new];
            dtl = newL;
            dtl.type = WorkSummaryListContent;
            
            [ar addObject:dtl];
        }
    }
    
    return ar;
}

#pragma mark --
#pragma mark -- tableView delegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WorkSummaryList * l = _datas[indexPath.row];
    if(l.rowHeight <= CaleRowHeightTag)
    {
        switch(l.type)
        {
            case WorkSummaryListEmpty:
            {
                l.rowHeight = [WorkSummaryEmptyCell caleHeight];
                break;
            }
            case WorkSummaryListContent:
            {
                l.rowHeight = [WorkSummaryCell caleHeight:tableView.width content:l.content];
                break;
            }
            default:
            {
                break;
            }
        }
    }
    return l.rowHeight;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self workSummaryData].count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WorkSummaryList * l = _datas[indexPath.row];
    switch(l.type)
    {
        case WorkSummaryListEmpty:
        {
            WorkSummaryEmptyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WorkSummaryEmptyCell"];
            if(cell == nil)
                cell = [[WorkSummaryEmptyCell alloc]initWithReuseIdentifier:@"WorkReportEmptyCell"];
            return cell;
            
            break;
        }
        case WorkSummaryListContent:
        {
            WorkSummaryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WorkSummaryListContent"];
            if(cell == nil)
            {
                cell = [[WorkSummaryCell alloc]initWithReuseIdentifier:@"WorkSummaryListContent"];
            }
            
            WorkSummaryList *bi = [self workSummaryData][indexPath.row];
            
            cell.szTag = bi.workSummaryId;
            
            cell.title =[NSString stringWithFormat:@"%@(%@)", bi.title,bi.createUser];
            cell.content = bi.content;
            cell.viewCount = bi.viewCount;
            cell.CommentCount = bi.commentCount;
            cell.createTime =  [bi.createTime toStringDate:NSDateFormatByyMd];
            
            return cell;
            
            break;
        }
        default:
        {
            break;
        }
    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [UIViewController closeKeyBoard];
    
    WorkSummaryList *info = [self workSummaryData][indexPath.row];
    
    XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
    
    if(_sourceType == MyWorkSummarySource)
    {
        p.param[WorkSummaryDetailViewControllerInfoParamKey] = info;
        [XUINavigationController pushViewControllerClass:[WorkSummaryDetailViewController class] withSwitchParam:p];
    }
    else if(_sourceType == LeaderSummarySource)
    {
        p.param[LeaderCommitWorkSummaryViewControllerInfoParamKey] = info;
        [XUINavigationController pushViewControllerClass:[LeaderCommitWorkSummaryViewController class] withSwitchParam:p];
    }
}

-(id)contentLastRefreshUpdateTimeOfTableView:(XUITableView *)tableview
{
    return _lastUpdatetime;
}

-(void)tableView:(XUITableView *)tableview refreshTableContent:(void (^)())asyncEndRefreshing
{
    if(_bRefreshing == YES)
        return;
  
    _bRefreshing = YES;
    [_manager stopRequest];
    
    _pageIndex = 1;
    [_manager getMyWorkSummarySourceType:_sourceType pageIndex:_pageIndex pageSize:_pageSize completion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         if(nResult == YES)
             _lastUpdatetime = [NSDate date];
         
         _bRefreshing = NO;
         
         [self requestComplete:nil funcationName:@"getMyWorkSummary" result:nResult output:list error:error];
     }];
}

#pragma mark --
#pragma mark -- loadMore delegate

- (void)loadMoreContentOfTableView:(XUITableView *)tableview
{
    if(_bLoadmoring == YES)
        return;
    
    if([_ctable.searchBar.searchText isEqualToString:@""] == NO)
    {
        _ctable.searchBar.searchText = @"";
        _bSearching = NO;
        [_searchDatas  removeAllObjects]; 
        [_ctable reloadData];
    }

    _bLoadmoring = YES;
    
    [tableview showLoadMoreStatus];
    
    _pageIndex ++;
    
    [_manager getMyWorkSummarySourceType:_sourceType pageIndex:_pageIndex pageSize:_pageSize completion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         [tableview hideLoadMoreStatus];
         
         _bLoadmoring = NO;

         [self requestComplete:nil funcationName:@"getMyWorkSummaryMore" result:nResult output:list error:error];
     }];
}

- (void)tableView:(XUITableView *)tableview didClickedLoadMoreFootView:(XUILoadMoreFootView *)sender
{
    [self loadMoreContentOfTableView:tableview];
}

#pragma mark --
#pragma mark -- observer

-(void)observerRSWDataOperationWorkSummaryModifyNotification:(NSNotification*)noti
{
    [_manager getMyWorkSummarySourceType:_sourceType pageIndex:_pageIndex pageSize:_pageSize completion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         _bRefreshing = NO;
         
         [self requestComplete:nil funcationName:@"getMyWorkSummary" result:nResult output:list error:error];
     }];
}

-(void)observerRSWDataOperationWorkSummaryDeleteNotification:(NSNotification*)noti
{
    [_manager getMyWorkSummarySourceType:_sourceType pageIndex:_pageIndex pageSize:_pageSize completion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         _bRefreshing = NO;
         
         [self requestComplete:nil funcationName:@"getMyWorkSummary" result:nResult output:list error:error];
     }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
